#!usr/bin/env python
# -*- coding:utf-8 -*-
"""
@author:'手机视界'
@file: install.py
@time: 2018/10/21
博客部署文件
# 安装yum源
"""

from subprocess import Popen, CalledProcessError, PIPE
import traceback
import os
import sys
import logging

logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(filename)s[line:%(lineno)d] [%(levelname)s] %(message)s',
                    datefmt='[%a, %d %b %Y %H:%M:%S]')


def shell(cmds, read=False):
    result = ''
    for cmd in cmds:
        logging.info("正在执行命令........%s" % cmd)
        try:
            result = Popen(cmd, stdout=PIPE, shell=True)
            logging.warning('read:%s' % (result.stdout.read()))
        except CalledProcessError:
            if 'collectstatic' in cmd:
                logging.warning("命令执行存在异常，不影响正常功能.....")
                continue
            msg = traceback.format_exc()
            logging.error("命令\'%s\'==执行失败，可联系作者QQ：942242856==\n%s,%s" % (cmd, result, msg))


# 安装yum源
version = sys.version[:3]
if version.__contains__('2.7'):
    i = raw_input('是否选择备份/etc/yum.repos.d/CentOS-Base.repo文件？yes or no :')
    host_ip = raw_input('请输入你的网站IP，如:127.0.0.1 :')
else:
    i = input('是否选择备份/etc/yum.repos.d/CentOS-Base.repo文件？yes or no :')
    host_ip = input('请输入你的网站IP，如:127.0.0.1 :')

if i in ['y', 'yes', 'Y', 'Yes', 'YES', '']:
    cmds = ["cp /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo_bbd_bak",
            "wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo", "yum clean all",
            "yum makecache"]
    if not os.path.exists("/etc/yum.repos.d/CentOS-Base.repo_bbd_bak"):
        shell(cmds)

# 下载网站源码
shell(['sudo yum install -y python34.x86_64 python34-devel.x86_64 nginx.x86_64 git gcc'])
# 安装虚拟机环境
os.system("python3 -m venv /usr/lib/bbd")
os.putenv('VIRTUAL_ENV', '/usr/lib/bbd')
os.system("pip install --upgrade pip")
# 下载网站源码 &&收集静态文件
bbd_dir = '/usr/lib/bbd/lib/python3.4/site-packages/bianbingdang'
git_url = 'https://gitee.com/bsxbl/author_manager.git '
static_dir = bbd_dir + '/static'
source_code = []
venv_source = "source /usr/lib/bbd/bin/activate;"
# 静态文件如果存在，删除重新收集
if os.path.exists(static_dir):
    logging.warning("正在删除文件夹...%s" % static_dir)
    source_code.append('rm -rf ' + static_dir)
    logging.warning("文件夹%s删除成功" % static_dir)

source_code.append(venv_source + 'python ' + bbd_dir + '/manage.py collectstatic')

# 下载源码，如果安装目录不存在则创建，否则升级
if not os.path.exists(bbd_dir):
    os.system('mkdir ' + bbd_dir)
    os.chdir(bbd_dir)
    logging.info("下载源码...........")
    os.system('git clone ' + git_url + bbd_dir)
else:
    logging.info("更新源码...........")
    os.chdir(bbd_dir)
    source_code.append('git pull')

# 切换到根目录
os.chdir(bbd_dir)
shell(source_code)
# 安装依赖 && 安装uwsgi
shell([venv_source + 'pip install uwsgi', venv_source + 'pip install -r ' + bbd_dir + '/requirements.txt'])

# 配置网站IP
os.chdir(bbd_dir)
with open(bbd_dir + '/deploy/hosts', 'wt') as hosts:
    hosts.write(host_ip)

shell(['cp ' + bbd_dir + '/deploy/bbd_base.conf ' + bbd_dir + '/deploy/bbd.conf'])

with open(bbd_dir + '/deploy/bbd.conf', 'r') as nginx_conf:
    conf = nginx_conf.read()

with open(bbd_dir + '/deploy/bbd.conf', 'w') as nginx_conf:
    nginx_conf.write(conf.replace('-server_name-', host_ip))

# 配置nginx
shell(['cp ' + bbd_dir + '/deploy/bbd.conf /etc/nginx/conf.d/'])

# 启动uwsgi
shell([venv_source + 'uwsgi --ini ' + bbd_dir + '/deploy/uwsgi.ini'])

# 启动nginx
shell(['systemctl restart nginx.service '])

# 设置防火墙
shell(['systemctl start firewalld.service', 'firewall-cmd --zone=public --add-port=80/tcp --permanent',
       'systemctl restart firewalld.service'])
